﻿Imports LiteDB

Public Class Version
    Private mItems As List(Of VersionItem)
    Private mSelectedVersionID As Integer
    Property SelectedVersionID As Integer
        Get
            Return mSelectedVersionID
        End Get
        Set(value As Integer)
            mSelectedVersionID = value
        End Set
    End Property
#Region "Get Properties"
    Public ReadOnly Property VersionList As List(Of VersionItem)
        Get
            Return mItems
        End Get
    End Property
    Public ReadOnly Property SelectedVersion() As VersionItem
        Get
            Return (From x In mItems Where x.VersionID = SelectedVersionID).First
        End Get
    End Property
#End Region
    Sub New()
        mItems = New List(Of VersionItem)
        LoadList()
    End Sub
    Private Sub LoadList()
        Using db As New LiteEngine(gApp.DatabaseFile)
            Dim a = (From x In db.GetCollection(Of VersionItem)(DTVersion).All).ToList
            mItems = (From x In a Where x.ApplicationID = gUDApp.SelectedAppID).ToList
        End Using
    End Sub
    Function Save(Data As VersionItem) As Integer
        Dim tAdd As Boolean
        Dim tNewID As Integer
        Dim n As VersionItem
        Using db As New LiteEngine(gApp.DatabaseFile)
            Dim col = db.GetCollection(Of VersionItem)(DTVersion)

            tAdd = False
            If Data.VersionID = 0 Then
                Try
                    tNewID = (From x In col.All Select x.VersionID).Max + 1
                Catch ex As Exception
                    tNewID = 1
                End Try
                Data.VersionID = tNewID
                tAdd = True
            End If

            If tAdd = False Then
                n = col.FindById(Data.VersionID)
                Dim a = (From x In mItems Where x.VersionID = Data.VersionID).First
                mItems.Remove(a)
            Else
                n = New VersionItem
                n.VersionID = Data.VersionID
                n.DateTimeCreated = DateFunctions.GetDateTimeString(Now)
            End If

            n.VersionNumber = Data.VersionNumber
            n.DateTimePublished = Data.DateTimePublished
            n.VersionFiles = Data.VersionFiles
            n.VersionStatus = Data.VersionStatus
            n.VersionNotes = Data.VersionNotes
            n.IsBeta = Data.IsBeta

            If tAdd = True Then
                col.Insert(n)
            Else
                col.Update(n)
            End If
            mItems.Add(n)
        End Using
        Return n.VersionID
    End Function
End Class
